<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle" >
              <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="htbh">
              <a-input :disabled="true" v-model="model.borrowApplyNo" placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date :disabled="true" placeholder="请选择申请时间" v-model="model.createTime" style="width: 100%"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
              <select-user-by-dep disabled :multi="false" v-model="model.proposer"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
              <j-select-depart disabled v-model="model.proposerDeptId"/>
            </a-form-model-item>
          </a-col>

          <a-divider>基本信息</a-divider>
          <a-col :span="8">
            <a-form-model-item label="签订公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyCompany">
              <select-company-input
                :disabled="formDisabled"
                v-model="model.applyCompany"
                @change="changeCompany"
                placeholder="请选择签订公司"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractId">
              <template v-if="formDisabled">
                <div class="contract_tag">
                  <a-tag v-for="(item,index) in contractList" :key="item.id" @click="goContratDetail1(item)" color="#1890FF" :style="{ margin: index!=contractList.length-1?'0 2px 2px 0':'0',cursor: 'pointer' }">{{item.htmc}}</a-tag>
                </div>
              </template>
              <template v-else>
                <select-contract-manager-input
                  :disabled="formDisabled"
                  v-model="model.contractId"
                  :multi="true"
                  :status = "'2'"
                  :allList="true"
                  showName
                  penetrate="mc"
                  class="p-select"
                  :signUnit ="this.companyVal"
                  :muitFlag="true"
                  @back="contractBack"/>
              </template>
              
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="是否外带" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="takeout">
              <j-dict-select-tag
                @input="isGiveBack"
                :disabled="formDisabled"
                type="radio"
                v-model="model.takeout"
                dictCode="yes_no"
                placeholder="请选择是否外带"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="showGiveBack">
            <a-form-model-item label="是否归还" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="giveBack">
              <j-dict-select-tag
                @input="isReturnDate"
                :disabled="formDisabled"
                type="radio"
                v-model="model.giveBack"
                dictCode="yes_no"
                placeholder="请选择是否归还"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="借阅日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="borrowDate">
<!--              <j-date :disabled="formDisabled" placeholder="请选择借阅日期" v-model="model.borrowDate" style="width: 100%"/>-->
              <a-date-picker
                show-time
                :disabled="formDisabled"
                placeholder="请选择借阅日期"
                v-model="borrowDate"
                @change="(date, dateStr) => {
                    this.$set(this.model, 'borrowDate', dateStr);
                    this.$set(this.model, 'predictReturnDate', undefined)
                    this.predictReturnDate = undefined;
                  }"
                :disabledDate="disabledEntriesEndDate"
                format="YYYY-MM-DD"
                style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="showReturnDate">
            <a-form-model-item label="预计归还日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="predictReturnDate">
<!--              <j-date
                :disabled="formDisabled"
                placeholder="请选择预计归还日期"
                v-model="model.predictReturnDate"
                style="width: 100%"/>-->

              <a-date-picker
                show-time
                :disabled="formDisabled"
                placeholder="请选择投标截止时间"
                v-model="predictReturnDate"
                @change="(date, dateStr) => { this.$set(this.model, 'predictReturnDate', dateStr) }"
                :disabledDate="disabledTenderEndDate"
                format="YYYY-MM-DD"
                style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="份数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
              <a-input-number
                :disabled="formDisabled"
                :max="99999999"
                :min="0"
                :precision="0"
                v-model="model.borrowCount"
                placeholder="请输入份数"
                style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="借阅事由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="borrowCause">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.borrowCause" placeholder="请输入借阅事由"></a-textarea>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" placeholder="请输入备注"></a-textarea>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyUpload">
              <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.applyUpload"></j-upload>
              <a-button v-else icon="download" @click="viewFile(model.applyUpload)">文件列表</a-button>
            </a-form-model-item>
          </a-col>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
        </a-row>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
      <ErpContractManagerPenetrate ref="erpContractManagerPenetrate"></ErpContractManagerPenetrate>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpOmcContractBorrowManagerFormPrint v-if="formBpm" class="print_style" id="contractborrowContent" :formData="model" :formDataHistory="formData"></ErpOmcContractBorrowManagerFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { validateBlankValue, viewFile } from '@/utils/util'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import moment from 'moment';
import { mapGetters } from 'vuex';
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin';
import SelectContractInput from '@/views/scy/components/SelectContractInput'
import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpOmcContractBorrowManagerFormPrint from './ErpOmcContractBorrowManagerFormPrint' // 打印
export default {
  name: 'ErpOmcContractBorrowManagerForm',
  mixins: [DisabledAuthFilterMixin, viewFile],
  components: {
    SelectCompanyInput, SelectUserByDep, SelectContractInput, SelectContractManagerInput, ViewFileModal,CommonFlowList, ErpOmcContractBorrowManagerFormPrint,
    ErpContractManagerPenetrate: () => import('@/views/scy/penetrate/ErpContractManagerPenetrate'),
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {
        takeout: 0,
        giveBack: 0
      },
      showCompany: false,
      // 显示是否归还的下拉框
      showGiveBack: false,
      // 显示归还时间选择框
      showReturnDate: false,
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      dataSource: [],
      validatorRules: {
        applyCompany: [
          { required: true, message: '请输入签订单位!' },
        ],
        applyUser: [
          { required: true, message: '请输入申请人!' }
          // { validator: (rule, value, callback) => validateBlankValue('erp_omc_contract_borrow_manager', 'apply_user', value, this.model.id, callback)},
        ],
        applyDept: [
          { required: true, message: '请输入申请部门!' },
          { validator: (rule, value, callback) => validateBlankValue('erp_omc_contract_borrow_manager', 'apply_dept', value, this.model.id, callback) }
        ],
        takeout: [
          { required: false, message: '请输入是否外带!' },
          { validator: (rule, value, callback) => validateBlankValue('erp_omc_contract_borrow_manager', 'takeout', value, this.model.id, callback) }
        ],
        contractId: [
          { required: true, message: '请输入合同名称!' },
          { validator: (rule, value, callback) => validateBlankValue('erp_omc_contract_borrow_manager', 'contract_name', value, this.model.id, callback) }
        ],
        borrowDate: [
          { required: true, message: '请输入借阅日期!' },
        ],
        predictReturnDate: [
          { required: true, message: '请选择预计归还日期!' },
        ],
        borrowCause: [
          { required: true, message: '请输入借阅事由!' },
          { validator: (rule, value, callback) => validateBlankValue('erp_omc_contract_borrow_manager', 'borrow_cause', value, this.model.id, callback) }
        ]
      },
      url: {
        add: '/api/erp/omc/contractmanager/erpOmcContractBorrowManager/add',
        edit: '/api/erp/omc/contractmanager/erpOmcContractBorrowManager/edit',
        queryById: '/api/erp/omc/contractmanager/erpOmcContractBorrowManager/queryById',
        generatedFormNumber: '/api/erp/base/generatedFormNumber'
      },
      unitDictCode: 'erp_company_files,file_name,id, del_flag = 0',
      borrowDate: undefined,
      predictReturnDate: undefined,
      companyVal: '-1',
      contractList: [],
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
  },
  methods: {
    ...mapGetters(['userInfo']),
    goContratDetail1(record){
      this.$refs.erpContractManagerPenetrate.initData(record.id);
      this.$refs.erpContractManagerPenetrate.visible=true;
    },
    // 显示是否归还
    isGiveBack(e) {
      if (e == '1') {
        this.validatorRules.takeout.required = true
        this.showGiveBack = true
        this.model.giveBack = 0
      } else {
        this.validatorRules.takeout.required = true
        this.showGiveBack = false
        this.model.giveBack = 0
        this.showReturnDate = false
        this.model.predictReturnDate = null
        // this.validatorRules.predictReturnDate.required = false
      }
    },
    // 显示预计归还时间
    isReturnDate(e) {
      if (e == '1') {
        // this.validatorRules.predictReturnDate.required = true
        this.showReturnDate = true
      } else {
        this.showReturnDate = false
        this.model.predictReturnDate = null
        // this.validatorRules.predictReturnDate.required = false
      }
    },
    add(value) {
      this.dataSource = [];
      this.borrowDate = undefined;
      this.predictReturnDate = undefined;
      this.edit(this.modelDefault);
      this.model.proposer = value.loginUser.empId;
      this.model.proposerDeptId = this.userInfo().deptId;
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      this.generatedFormNumber();
    },
    generatedFormNumber() {
      this.userName = this.userInfo().empName;//当前登录人名称
      getAction(this.url.generatedFormNumber, { prefix: 'HTJY', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'borrowApplyNo', res.result)
        }
      })
    },
    edit(record) {
      this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      this.borrowDate = this.model.borrowDate;
      this.predictReturnDate = this.model.predictReturnDate;
      if (this.model.takeout == 1) {
        this.showGiveBack = true
      }else { // fix:BUG#6100 【项目合同借阅】是否外带为否，详情页展示是否归还字段
        this.showGiveBack = false
      }
      if (this.model.takeout == 1 && this.model.giveBack == 1) {
        this.showReturnDate = true
      } else {
        this.showReturnDate = false
      }
      // fix:BUG#4947 合同借阅申请】编辑页面，合同名称弹框数据为空 start
      if(!!this.model.applyCompany){
        this.companyVal = this.model.applyCompany
      }
      this.contractList = []
      if(this.model.contractId){
        this.model.contractId.split(',').forEach((v,index) => {
          this.contractList.push({
            htmc: this.model.contractId_dictText.split(',')[index],
            id: v
          })
        })
      }
      // fix:BUG#4947 合同借阅申请】编辑页面，合同名称弹框数据为空 end
      this.visible = true;
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        // 审批中可以看到申请公司信息
        this.showCompany = true
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },

    submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      this.model.hasReturned = '0'
      httpAction(httpurl, this.model, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable');
        }
      }).catch((error) => {
        that.$emit('unButtonDisable', error);
      }).finally(() => {
        that.confirmLoading = false;
      })
    },
    changeCompany(val) {
        this.companyVal = val;
        this.$set(this.model, 'contractId', '')
    },
    contractBack(item) {
      this.contractName = []
      for (var i = 0; i < item.length; i++) {
        this.contractName.push(item[i].htmc);
      }
      this.model.contractName = this.contractName.join(",");
       // this.$set(this.model, 'contractName', item[0].htmc)
    },
    disabledEntriesEndDate(currentDate) {
      return currentDate < moment(this.model.createTime).subtract('day')
    },
    disabledTenderEndDate(currentDate) {
      return currentDate < moment(this.model.borrowDate).subtract('day')
    },

    // 点击打印
    onPrint () {
        let print = new Print({
          el: '#contractborrowContent',
          popTitle: '项目合同借阅申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
  }
}
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
<style lang="less" scoped>
.contract_tag{
  background: #fafafa;
  width: 100%;
  min-height: 32px;
  border: 1px solid #d9d9d9;
  border-top-width: 1.02px;
  border-radius: 4px;
  outline: none;
  padding: 4px 11px;
  display: flex;
  flex-wrap: wrap;
}
</style>